package com.music.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.music.server.pojo.ListSong;
import com.music.server.mapper.ListSongMapper;
import com.music.server.pojo.Song;
import com.music.server.pojo.SongList;
import com.music.server.service.ListSongService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.music.server.service.SongService;
import com.music.server.vo.ListSongVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 歌单包含歌曲列表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-03-09
 */
@Service
public class ListSongServiceImpl extends ServiceImpl<ListSongMapper, ListSong> implements ListSongService {

    @Autowired
    private SongService songService;

    @Override
    public Map<String, Object> page(Integer pageNum, Integer size, ListSongVo listSongVo) {
        if (listSongVo.getSongListId() == null) return null;
        List<Integer> songIds = new ArrayList<>();
        if (listSongVo.getSongName() != null) {
            QueryWrapper<Song> songQueryWrapper = new QueryWrapper<>();
            songQueryWrapper.like("name", listSongVo.getSongName());
            List<Song> list = songService.list(songQueryWrapper);
            for (Song song : list) {
                songIds.add(song.getId());
            }

        }
        Page<ListSong> songPage = new Page<>(pageNum, size);
        QueryWrapper<ListSong> songQueryWrapper = new QueryWrapper<>();
        if (!CollectionUtils.isEmpty(songIds)) {
            songQueryWrapper.in("song_id", songIds);
        }
        songQueryWrapper.eq("song_list_id", listSongVo.getSongListId());

        this.page(songPage, songQueryWrapper);
        Map<String, Object> data = new HashMap<>();
        data.put("total", songPage.getTotal());
        List<ListSong> records = songPage.getRecords();
        for (ListSong listSong : records) {
            Song song = songService.getById(listSong.getSongId());
            listSong.setSongName(song.getName());
        }
        data.put("list", records);
        return data;
    }
}
